package com.example.secondhandshop.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.Chatitem;
import com.example.secondhandshop.model.ChatitemModel;
import com.example.secondhandshop.model.NewMassageModel;
import com.example.secondhandshop.model.ReadModel;
import com.example.secondhandshop.ui.adapter.AllchatitemAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class MessageDetails extends AppCompatActivity implements ChatitemModel.OnProductsFetchedListener {
    private RecyclerView recyclerView;
    private AllchatitemAdapter allchatitemAdapter;
    private TextView tvsellername;
    private ChatitemModel chatitemModel;
    private NewMassageModel newMassageModel;
    private TextView content;
    private Button btsent;
    private int sellerId=0;
    private List<Chatitem> recivechatitem=new ArrayList<>();
    private int unread=0;
    private String avatar;
    public ChatitemModel.OnProductsFetchedListener listener1;
    public ReadModel.OnProductsFetchedListener listener2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        listener1=this;
        setContentView(R.layout.activity_message_details);
        recyclerView=findViewById(R.id.recyclerViewMessages);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        AllchatitemAdapter adapter = new AllchatitemAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);
        tvsellername = findViewById(R.id.textViewUsername);
        // 获取Intent并处理数据
        Intent intent = getIntent();
        if (intent != null) {
            avatar = intent.getStringExtra("magic"); // 假设头像是一个字符串
            sellerId = intent.getIntExtra("sellerId",-1);
            System.out.println("sellerId is"+sellerId);
            if(sellerId!=-1){
                chatitemModel=new ChatitemModel();
//                chatitemModel.getallchatfrom(LoginAcitivity.userid, sellerId, listener1);
              chatitemModel.getallchatfrom(552, 583, listener1);
            }else {
                System.out.println("sellerid==null");
            }
            String sellername = intent.getStringExtra("sellername");
            // 设置卖家名称
            if (sellername != null) {
                tvsellername.setText(sellername);
            } else {
                // 处理sellername为null的情况
                tvsellername.setText("Unknown Seller");
            }
            unread = intent.getIntExtra("unread", 0);
        } else {
            Toast.makeText(MessageDetails.this, "获取intent错误", Toast.LENGTH_SHORT).show();
        }
        newMassageModel=new NewMassageModel();
        content=findViewById(R.id.editTextMessage);
        btsent=findViewById(R.id.buttonSend);
        btsent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(content.getText()==null){
                    Toast.makeText(MessageDetails.this, "消息不能为空", Toast.LENGTH_SHORT).show();
                }else {
                    NewMassageModel.OnProductsFetchedListener listener=new NewMassageModel.OnProductsFetchedListener() {
                        @Override
                        public void onSuccess() {
                            chatitemModel.getallchatfrom(552, 583, listener1);
                            content.setText(null);
                        }

                        @Override
                        public void onFailure() {
                        }

                    };
//                    newMassageModel.NewMassageModel(sellerId,LoginAcitivity.userid,content.getText().toString(),listener);
                  newMassageModel.NewMassageModel(583,LoginAcitivity.userid,content.getText().toString(),listener);
                }
            }
        });
    }
    public void onSuccess(List<Chatitem> chatitems) {
        System.out.println("chatitems is "+chatitems);
        recivechatitem = chatitems.stream().filter(item -> item.getFromUserId()!=LoginAcitivity.userid)
                .collect(Collectors.toList());
        System.out.println("recivechatitem  is "+recivechatitem);
        Read1(unread,recivechatitem);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Collections.reverse(chatitems);
                // 如果适配器还没有被初始化，那么现在初始化它
                if (allchatitemAdapter == null) {
                    allchatitemAdapter = new AllchatitemAdapter(chatitems);
                    recyclerView.setAdapter(allchatitemAdapter);
                }
                else {
                        allchatitemAdapter.updateChatItems(chatitems);
                        allchatitemAdapter.notifyDataSetChanged();
                }
                if (recyclerView != null && chatitems.size() > 0) {
                    recyclerView.scrollToPosition(chatitems.size() - 1);
                }
            }
        });
    }
    @Override
    public void onFailure(String error) {
       Toast.makeText(this, "Failed to fetch chat items: " + error, Toast.LENGTH_LONG).show();
    }
    // 其他方法（如果需要的话）...
    public void Read1(int unread,List<Chatitem> chatitems){
        System.out.println("unread"+unread);
        System.out.println(chatitems);
        System.out.println(chatitems.size());
        ReadModel readModel=new ReadModel();
        for(int i=0;i<10;i++){
            listener2=new ReadModel.OnProductsFetchedListener() {
                @Override
                public void onSuccess(int i) {
                    chatitems.get(i).setStatus(true);
                }
                @Override
                public void onFailure(int i) {
                }
            };
            readModel.Isread(i,chatitems.get(i).getId(),listener2);
        }
        Intent intent = new Intent("MessageFragemt.class");
        intent.putExtra("key", 0);
        intent.putExtra("fromuserid", chatitems.get(0).getFromUserId());
        sendBroadcast(intent);
    }
}